import { View, Text, TextInput, TouchableOpacity, FlatList, Image, StyleSheet, KeyboardAvoidingView, Platform, ActivityIndicator, Alert, StatusBar, SafeAreaView, Keyboard, Animated } from 'react-native';
import React, { useState, useEffect, useRef } from 'react';
import { useLocalSearchParams, Stack, useRouter } from 'expo-router';
import { useTheme } from '../../context/ThemeContext';
import { MaterialCommunityIcons, Ionicons } from '@expo/vector-icons';
import { getPrivateHistory, sendMessage, MessageType, markMessagesAsRead, recallMessage } from '../../services/chatService';
import { format, isToday, isYesterday } from 'date-fns';
import { useAppSelector } from '../../store/hooks';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
// import { zh } from 'date-fns/locale';

export default function PrivateChatScreen() {
  const { id, name } = useLocalSearchParams();
  const { isDarkMode } = useTheme();
  const router = useRouter();
  const insets = useSafeAreaInsets(); // 获取安全区域的内边距
  
  const [messages, setMessages] = useState<MessageType[]>([]);
  const [inputText, setInputText] = useState('');
  const [loading, setLoading] = useState(true);
  const [sending, setSending] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [showExtraFeatures, setShowExtraFeatures] = useState(false);
  const [keyboardHeight, setKeyboardHeight] = useState(0);
  const [isKeyboardVisible, setIsKeyboardVisible] = useState(false);
  
  const flatListRef = useRef<FlatList>(null);
  const inputRef = useRef<TextInput>(null);
  const keyboardAnim = useRef(new Animated.Value(0)).current;
  
  // 从Redux存储中获取当前用户信息
  const currentUser = useAppSelector(state => state.user.currentUser);
  const userId = currentUser?.id || 0;
  
  // 加载聊天记录
  const loadMessages = async (page: number = 1) => {
    try {
      if (page === 1) {
        setLoading(true);
      }
      
      // 使用实际API获取聊天记录
      const response = await getPrivateHistory(Number(id), page);
      
      if (page === 1) {
        setMessages(response.records);
      } else {
        setMessages(prev => [...response.records, ...prev]);
      }
      
      setCurrentPage(page);
      setHasMore(page < response.pages);
      
      // 标记消息为已读
      const unreadIds = response.records
        .filter(msg => msg.status === 0 && msg.fromUserId !== userId)
        .map(msg => msg.id);
      
      if (unreadIds.length > 0) {
        await markMessagesAsRead(unreadIds);
      }
      
    } catch (error: any) {
      console.error('加载消息记录失败:', error);
      
      // 处理特定错误
      if (error.response?.data?.code === 400 && error.response?.data?.message.includes('不是您的好友')) {
        Alert.alert('提示', '对方不是您的好友，无法查看聊天记录');
      } else if (error.response?.data?.code === 404) {
        Alert.alert('提示', '用户不存在');
      } else {
        Alert.alert('错误', '加载消息记录失败，请重试');
      }
    } finally {
      setLoading(false);
    }
  };
  
  // 首次加载消息
  useEffect(() => {
    if (userId && id) {
      loadMessages();
    }
  }, [id, userId]);
  
  // 消息加载完成后滚动到底部
  useEffect(() => {
    if (!loading && messages.length > 0) {
      setTimeout(() => {
        flatListRef.current?.scrollToEnd({ animated: false });
      }, 200);
    }
  }, [loading, messages.length]);
  
  // 监听键盘事件
  useEffect(() => {
    const keyboardWillShowListener = Keyboard.addListener(
      Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow',
      (e) => {
        setIsKeyboardVisible(true);
        setKeyboardHeight(e.endCoordinates.height);
        
        Animated.timing(keyboardAnim, {
          toValue: 1,
          duration: Platform.OS === 'ios' ? 250 : 50,
          useNativeDriver: false,
        }).start();
        
        // 键盘弹出时，滚动到底部
        setTimeout(() => {
          flatListRef.current?.scrollToEnd({ animated: true });
        }, 50);
      }
    );
    
    const keyboardWillHideListener = Keyboard.addListener(
      Platform.OS === 'ios' ? 'keyboardWillHide' : 'keyboardDidHide',
      () => {
        setIsKeyboardVisible(false);
        
        Animated.timing(keyboardAnim, {
          toValue: 0,
          duration: Platform.OS === 'ios' ? 250 : 50,
          useNativeDriver: false,
        }).start();
      }
    );
    
    return () => {
      keyboardWillShowListener.remove();
      keyboardWillHideListener.remove();
    };
  }, []);
  
  // 发送消息
  const handleSend = async () => {
    if (!inputText.trim()) return;
    
    try {
      setSending(true);
      
      // 调用API发送消息
      const messageId = await sendMessage(Number(id), 0, inputText.trim(), 0); // 0表示文本消息
      
      // 添加新消息到列表
      const newMessage: MessageType = {
        id: messageId,
        fromUserId: userId,
        fromUserName: currentUser?.userName || '我',
        fromUserAvatar: currentUser?.userAvatar || '',
        toId: Number(id),
        chatType: 0,
        content: inputText.trim(),
        contentType: 0,
        status: 1,
        createTime: format(new Date(), 'yyyy-MM-dd HH:mm:ss')
      };
      
      setMessages(prev => [...prev, newMessage]);
      setInputText('');
      
      // 滚动到底部
      setTimeout(() => {
        flatListRef.current?.scrollToEnd({ animated: true });
      }, 100);
      
    } catch (error) {
      console.error('发送消息失败:', error);
      Alert.alert('错误', '发送消息失败，请重试');
    } finally {
      setSending(false);
    }
  };
  
  // 加载更多消息
  const handleLoadMore = () => {
    if (hasMore && !loading) {
      loadMessages(currentPage + 1);
    }
  };
  
  // 长按消息处理
  const handleLongPress = (message: MessageType) => {
    // 仅允许撤回自己的消息且在2分钟内
    const canRecall = message.fromUserId === userId && 
      new Date().getTime() - new Date(message.createTime).getTime() <= 2 * 60 * 1000;
    
    Alert.alert(
      '消息操作',
      '',
      [
        { text: '复制', onPress: () => {
          // 复制功能
          Alert.alert('提示', '已复制内容到剪贴板');
        }},
        canRecall ? 
          { text: '撤回', onPress: () => handleRecall(message.id) } : 
          { text: '转发', onPress: () => {
            // 转发功能
            Alert.alert('提示', '转发功能正在开发中');
          }},
        { text: '取消', style: 'cancel' }
      ]
    );
  };
  
  // 撤回消息
  const handleRecall = async (messageId: number) => {
    try {
      // 调用API撤回消息
      const success = await recallMessage(messageId);
      
      if (success) {
        // 更新消息状态
        setMessages(prev => 
          prev.map(msg => 
            msg.id === messageId 
              ? { ...msg, content: '此消息已撤回', status: 2 } 
              : msg
          )
        );
      }
      
    } catch (error) {
      console.error('撤回消息失败:', error);
      Alert.alert('错误', '撤回消息失败，请重试');
    }
  };
  
  // 格式化时间
  const formatTime = (timeStr: string) => {
    const date = new Date(timeStr);
    const now = new Date();
    
    if (isToday(date)) {
      return format(date, 'HH:mm');
    } else if (isYesterday(date)) {
      return `昨天 ${format(date, 'HH:mm')}`;
    } else if (date.getFullYear() === now.getFullYear()) {
      return format(date, 'MM-dd HH:mm');
    } else {
      return format(date, 'yyyy-MM-dd HH:mm');
    }
  };
  
  // 显示消息时间分隔线
  const shouldShowTimestamp = (currentMsg: MessageType, prevMsg: MessageType | null) => {
    if (!prevMsg) return true;
    
    const currentTime = new Date(currentMsg.createTime).getTime();
    const prevTime = new Date(prevMsg.createTime).getTime();
    
    // 如果消息时间间隔超过5分钟，显示时间戳
    return (currentTime - prevTime) > 5 * 60 * 1000;
  };
  
  // 渲染消息项
  const renderMessageItem = ({ item, index }: { item: MessageType; index: number }) => {
    const isMyMessage = item.fromUserId === userId;
    const prevMsg = index > 0 ? messages[index - 1] : null;
    const showTimestamp = shouldShowTimestamp(item, prevMsg);
    
    return (
      <>
        {showTimestamp && (
          <View style={styles.timestampContainer}>
            <Text style={[
              styles.timestampText,
              { color: isDarkMode ? '#BBBBBB' : '#999999' }
            ]}>
              {formatTime(item.createTime)}
            </Text>
          </View>
        )}
        
        <TouchableOpacity
          style={[
            styles.messageContainer,
            isMyMessage ? styles.myMessageContainer : styles.otherMessageContainer
          ]}
          activeOpacity={0.8}
          onLongPress={() => handleLongPress(item)}
        >
          {/* 隐藏的Text组件防止警告 */}
          <Text style={{ height: 0, width: 0, opacity: 0 }}>.</Text>
          
          {!isMyMessage && (
            <Image 
              source={{ uri: item.fromUserAvatar || 'https://via.placeholder.com/36' }} 
              style={styles.avatar}
            />
          )}
          
          <View style={styles.messageContentContainer}>
            {!isMyMessage && (
              <Text style={[styles.nameText, { color: isDarkMode ? '#BBBBBB' : '#888888' }]}>
                {item.fromUserName}
              </Text>
            )}
            
            <View style={[
              styles.messageBubble,
              isMyMessage ? 
                [styles.myMessageBubble, { backgroundColor: isDarkMode ? '#007AFF' : '#4A90F1' }] : 
                [styles.otherMessageBubble, { backgroundColor: isDarkMode ? '#333333' : '#FFFFFF' }],
              item.status === 2 && { backgroundColor: isDarkMode ? '#555555' : '#EEEEEE' } // 已撤回消息样式
            ]}>
              {item.contentType === 0 ? (
                <Text style={[
                  styles.messageText,
                  { color: isMyMessage ? '#FFFFFF' : (isDarkMode ? '#FFFFFF' : '#333333') },
                  item.status === 2 && { fontStyle: 'italic', color: isDarkMode ? '#BBBBBB' : '#999999' } // 已撤回消息样式
                ]}>
                  {item.content}
                </Text>
              ) : item.contentType === 1 ? (
                // 图片消息
                <Image 
                  source={{ uri: item.content }} 
                  style={styles.imageMessage} 
                  resizeMode="cover"
                />
              ) : (
                // 其他类型消息
                <Text style={[
                  styles.messageText,
                  { color: isMyMessage ? '#FFFFFF' : (isDarkMode ? '#FFFFFF' : '#333333') }
                ]}>
                  {item.contentType === 2 ? '[语音消息]' : 
                   item.contentType === 3 ? '[视频消息]' : 
                   item.contentType === 4 ? '[文件]' : '未知消息类型'}
                </Text>
              )}
            </View>
          </View>
          
          {isMyMessage && (
            <Image 
              source={{ uri: currentUser?.userAvatar || 'https://via.placeholder.com/36' }} 
              style={styles.avatar}
            />
          )}
        </TouchableOpacity>
      </>
    );
  };
  
  // 处理额外功能按钮点击
  const handleExtraFeaturePress = (feature: string) => {
    Alert.alert('提示', `${feature}功能正在开发中`);
    setShowExtraFeatures(false);
  };
  
  // 返回按钮处理
  const handleGoBack = () => {
    router.back();
  };

  // 渲染消息列表
  return (
    <View style={{ flex: 1, backgroundColor: isDarkMode ? '#121212' : '#F5F5F5' }}>
      <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
      
      {/* 自定义导航栏 */}
      <SafeAreaView style={{ backgroundColor: isDarkMode ? '#1E1E1E' : '#FFFFFF' }}>
        <View style={[
          styles.header,
          { backgroundColor: isDarkMode ? '#1E1E1E' : '#FFFFFF' }
        ]}>
          <TouchableOpacity onPress={handleGoBack} style={styles.backButton}>
            <Ionicons name="chevron-back" size={24} color={isDarkMode ? '#FFFFFF' : '#333333'} />
          </TouchableOpacity>
          <Text style={[
            styles.headerTitle,
            { color: isDarkMode ? '#FFFFFF' : '#333333' }
          ]}>
            {String(name)} {/* 确保name是字符串 */}
          </Text>
          <TouchableOpacity onPress={() => router.push(`/friend/profile/${id}`)}>
            <MaterialCommunityIcons 
              name="dots-vertical" 
              size={24} 
              color={isDarkMode ? '#FFFFFF' : '#333333'} 
            />
          </TouchableOpacity>
        </View>
      </SafeAreaView>
      
      <KeyboardAvoidingView 
        style={{ flex: 1 }} 
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        keyboardVerticalOffset={Platform.OS === 'ios' ? 100 : 40}
      >
        <View style={{ flex: 1 }}>
          {/* 消息列表 */}
          {loading && messages.length === 0 ? (
            <View style={styles.loadingContainer}>
              <ActivityIndicator size="large" color={isDarkMode ? '#3B82F6' : '#2563EB'} />
              <Text style={{ color: isDarkMode ? '#BBBBBB' : '#666666', marginTop: 10 }}>
                加载消息中...
              </Text>
            </View>
          ) : (
            <FlatList
              ref={flatListRef}
              data={messages}
              renderItem={renderMessageItem}
              keyExtractor={item => item.id.toString()}
              contentContainerStyle={[
                styles.messagesList,
                { paddingBottom: insets.bottom + 70 } // 确保底部有足够空间
              ]}
              onEndReached={handleLoadMore}
              onEndReachedThreshold={0.1}
              inverted={false}
              ListEmptyComponent={
                <View style={styles.emptyContainer}>
                  <Text style={{ color: isDarkMode ? '#BBBBBB' : '#999999' }}>
                    没有消息记录，发送第一条消息开始聊天吧
                  </Text>
                </View>
              }
              ListHeaderComponent={
                hasMore ? (
                  <View style={styles.loadMoreContainer}>
                    <ActivityIndicator size="small" color={isDarkMode ? '#3B82F6' : '#2563EB'} />
                    <Text style={{ color: isDarkMode ? '#BBBBBB' : '#999999', marginLeft: 10 }}>
                      加载更多...
                    </Text>
                  </View>
                ) : null
              }
            />
          )}
          
          {/* 额外功能面板 */}
          {showExtraFeatures && (
            <View style={[
              styles.extraFeaturesContainer,
              { 
                backgroundColor: isDarkMode ? '#1A1A1A' : '#FFFFFF',
                bottom: isKeyboardVisible ? keyboardHeight : 0,
              }
            ]}>
              <TouchableOpacity 
                style={styles.extraFeatureButton}
                onPress={() => handleExtraFeaturePress('图片')}
              >
                <View style={styles.extraFeatureIconContainer}>
                  <MaterialCommunityIcons name="image" size={24} color="#FFFFFF" />
                </View>
                <Text style={{ color: isDarkMode ? '#FFFFFF' : '#333333', marginTop: 5 }}>图片</Text>
              </TouchableOpacity>
              
              <TouchableOpacity 
                style={styles.extraFeatureButton}
                onPress={() => handleExtraFeaturePress('视频通话')}
              >
                <View style={styles.extraFeatureIconContainer}>
                  <MaterialCommunityIcons name="video" size={24} color="#FFFFFF" />
                </View>
                <Text style={{ color: isDarkMode ? '#FFFFFF' : '#333333', marginTop: 5 }}>视频通话</Text>
              </TouchableOpacity>
              
              <TouchableOpacity 
                style={styles.extraFeatureButton}
                onPress={() => handleExtraFeaturePress('语音')}
              >
                <View style={styles.extraFeatureIconContainer}>
                  <MaterialCommunityIcons name="microphone" size={24} color="#FFFFFF" />
                </View>
                <Text style={{ color: isDarkMode ? '#FFFFFF' : '#333333', marginTop: 5 }}>语音</Text>
              </TouchableOpacity>
              
              <TouchableOpacity 
                style={styles.extraFeatureButton}
                onPress={() => handleExtraFeaturePress('文件')}
              >
                <View style={styles.extraFeatureIconContainer}>
                  <MaterialCommunityIcons name="file-document" size={24} color="#FFFFFF" />
                </View>
                <Text style={{ color: isDarkMode ? '#FFFFFF' : '#333333', marginTop: 5 }}>文件</Text>
              </TouchableOpacity>
            </View>
          )}
        </View>
        
        {/* 输入框 */}
        <View style={[
          styles.inputWrapper,
          { 
            backgroundColor: isDarkMode ? '#1A1A1A' : '#FFFFFF',
            borderTopColor: isDarkMode ? '#333333' : '#EEEEEE',
            paddingBottom: Math.max(insets.bottom, 5),
          }
        ]}>
          <View style={[
            styles.inputContainer,
            { backgroundColor: isDarkMode ? '#1A1A1A' : '#FFFFFF' }
          ]}>
            <TouchableOpacity 
              style={styles.voiceButton}
              onPress={() => handleExtraFeaturePress('语音')}
            >
              <MaterialCommunityIcons name="microphone" size={24} color={isDarkMode ? '#BBBBBB' : '#666666'} />
            </TouchableOpacity>
            
            <TextInput
              ref={inputRef}
              style={[
                styles.input,
                { 
                  backgroundColor: isDarkMode ? '#2A2A2A' : '#F0F0F0',
                  color: isDarkMode ? '#FFFFFF' : '#000000'
                }
              ]}
              placeholder="输入消息..."
              placeholderTextColor={isDarkMode ? '#999999' : '#999999'}
              value={inputText}
              onChangeText={setInputText}
              multiline
              onFocus={() => {
                // 聚焦时滚动到底部
                setTimeout(() => {
                  flatListRef.current?.scrollToEnd({ animated: true });
                }, 100);
              }}
            />
            
            <TouchableOpacity
              style={styles.extraButton}
              onPress={() => {
                setShowExtraFeatures(!showExtraFeatures);
                if (isKeyboardVisible) {
                  Keyboard.dismiss();
                }
              }}
            >
              <MaterialCommunityIcons name="plus-circle" size={24} color={isDarkMode ? '#BBBBBB' : '#666666'} />
            </TouchableOpacity>
            
            {inputText.trim() ? (
              <TouchableOpacity
                style={[
                  styles.sendButton,
                  { backgroundColor: isDarkMode ? '#3B82F6' : '#2563EB' }
                ]}
                onPress={handleSend}
                disabled={sending}
              >
                {sending ? (
                  <ActivityIndicator size="small" color="#FFFFFF" />
                ) : (
                  <MaterialCommunityIcons name="send" size={20} color="#FFFFFF" />
                )}
              </TouchableOpacity>
            ) : (
              <TouchableOpacity
                style={styles.emojiButton}
                onPress={() => handleExtraFeaturePress('表情')}
              >
                <MaterialCommunityIcons name="emoticon" size={24} color={isDarkMode ? '#BBBBBB' : '#666666'} />
              </TouchableOpacity>
            )}
          </View>
        </View>
      </KeyboardAvoidingView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 15,
    height: 56,
  },
  backButton: {
    padding: 5,
  },
  headerTitle: {
    fontSize: 17,
    fontWeight: '600',
    flex: 1,
    textAlign: 'center',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  messagesList: {
    padding: 10,
    flexGrow: 1,
  },
  messageContainer: {
    flexDirection: 'row',
    marginVertical: 5,
    alignItems: 'flex-end',
  },
  myMessageContainer: {
    justifyContent: 'flex-end',
  },
  otherMessageContainer: {
    justifyContent: 'flex-start',
  },
  avatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
  },
  messageBubble: {
    maxWidth: '70%',
    padding: 10,
    borderRadius: 16,
    marginHorizontal: 8,
  },
  myMessageBubble: {
    borderBottomRightRadius: 5,
  },
  otherMessageBubble: {
    borderBottomLeftRadius: 5,
  },
  messageText: {
    fontSize: 16,
    lineHeight: 22,
  },
  imageMessage: {
    width: 150,
    height: 200,
    borderRadius: 8,
  },
  timestampContainer: {
    alignItems: 'center',
    marginVertical: 10,
  },
  timestampText: {
    fontSize: 12,
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 10,
    backgroundColor: 'rgba(0, 0, 0, 0.1)',
  },
  inputWrapper: {
    borderTopWidth: 1,
    paddingVertical: 8,
    paddingHorizontal: 0,
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 10,
  },
  voiceButton: {
    marginRight: 8,
    padding: 5,
  },
  input: {
    flex: 1,
    borderRadius: 20,
    paddingHorizontal: 15,
    paddingVertical: 8,
    maxHeight: 80,
    minHeight: 36,
  },
  extraButton: {
    marginLeft: 8,
    padding: 5,
  },
  emojiButton: {
    marginLeft: 8,
    padding: 5,
  },
  sendButton: {
    width: 36,
    height: 36,
    borderRadius: 18,
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: 8,
  },
  extraFeaturesContainer: {
    position: 'absolute',
    left: 0,
    right: 0,
    flexDirection: 'row',
    padding: 15,
    borderTopWidth: 1,
    borderTopColor: '#EEEEEE',
    paddingBottom: 20,
  },
  extraFeatureButton: {
    alignItems: 'center',
    marginRight: 20,
  },
  extraFeatureIconContainer: {
    width: 45,
    height: 45,
    borderRadius: 10,
    backgroundColor: '#3B82F6',
    justifyContent: 'center',
    alignItems: 'center',
  },
  emptyContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: 100,
  },
  loadMoreContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 10,
  },
  messageContentContainer: {
    flex: 1,
    flexDirection: 'column',
    marginHorizontal: 8,
  },
  nameText: {
    fontSize: 12,
    marginBottom: 2,
  },
}); 